#!/usr/bin/env python
# -*- coding:utf-8 -*-
import MySQLdb
from DBUtils.PooledDB import PooledDB

from core.db import BaseDB


class Database(BaseDB):
    def __init__(self, *args, **kwargs):
        BaseDB.__init__(self, *args, **kwargs)
        self.min_cached = kwargs.get('min_cached', 5)
        self.host = kwargs.get('host', 'localhost')
        self.port = kwargs.get('port', 3306)
        self.user = kwargs.get('user', 'root')
        self.password = kwargs.get('password', '')
        self.database = kwargs.get('database', 'crawler')
        self.charset = kwargs.get('charset', 'utf8')
        self.pool = None

    def init(self, *args, **kwargs):
        self.pool = PooledDB(MySQLdb, self.min_cached, host=self.host, user=self.user, passwd=self.password,
                             db=self.database, port=self.port, charset=self.charset)

    def get_connect(self, *args, **kwargs):
        return self.pool.connection()

    def close(self, *args, **kwargs):
        self.pool.close()
